//
//  ComposeViewController.swift
//  Weibo10
//
//  Created by Leon on 15/10/25.
//  Copyright © 2015年 Leon. All rights reserved.
//

import UIKit

class ComposeViewController: UIViewController {
    
    // MARK: - 监听事件
///  关闭按钮
    @objc private func close() {
        // 关闭键盘
        textView.resignFirstResponder()
        dismissViewControllerAnimated(true, completion: nil)
    }
///  发送微博按钮
    @objc private func compose() {
        let text = textView.emoticonText
        print(text)
        
        let image = UIImage(named: "123")
        
        
        NetworkTools.shareTools.sendStatus(text, image: image) { (result, error) -> () in
            print(result)
        }
        
   
//        NetworkTools.shareTools.sendStatus(text) { (result, error) -> () in
//            print(result)
//        }
    }
///  表情键盘按钮
    @objc private func selectEmoticon() {
        
        // 1 关闭键盘
        textView.resignFirstResponder()
        
        // 2 替换键盘
        textView.inputView = textView.inputView == nil ? emoticonView : nil
        
        // 3 激活键盘
        textView.becomeFirstResponder()
    }
///  KVO监听键盘变化
    @objc private func keyboardChange(notify: NSNotification) {
        
        print(notify)
        let dict = notify.userInfo!
        
        // 1. 获取目标的 rect - 字典中的`结构体`是 NSValue
        let rect = (dict["UIKeyboardFrameEndUserInfoKey"] as! NSValue).CGRectValue()
        let changH = rect.origin.y - UIScreen.mainScreen().bounds.height
        // 动画时间
        let duration = (dict["UIKeyboardAnimationDurationUserInfoKey"] as! NSNumber).doubleValue
        // 动画曲线
        let curve = (dict["UIKeyboardAnimationCurveUserInfoKey"] as! NSNumber).integerValue
        
        // 2 更新约束
        toolBar.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(view.snp_bottom).offset(changH)
        }
        // 3 动画
        UIView.animateWithDuration(duration) { () -> Void in
            
            // 设置动画曲线
            /**
            曲线值 = 7
            － 如果之前的动画没有完成，有启动了其他的动画，让动画的图层直接运动到后续动画的目标位置
            － 一旦设置了 `7`，动画时长无效，动画时长统一变成 0.5s
            */
            UIView.setAnimationCurve(UIViewAnimationCurve(rawValue: curve)!)
            
            self.view.layoutIfNeeded()
        }
        
        // 调试动画时长 － keyPath 将动画添加到图层
        let anim = toolBar.layer.animationForKey("position")
        print("动画时长 \(anim?.duration)")
    }

    // MARK: - 视图声明周期
    override func loadView() {
        super.loadView()
        // 避免此处打印造成循环引用
        view = UIView()
        
        setupUI()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // 叫出键盘
        textView.becomeFirstResponder()
        // 监听键盘
        NSNotificationCenter.defaultCenter().addObserver(self,
            selector: "keyboardChange:",
            name: UIKeyboardWillChangeFrameNotification,
            object: nil)
    }
    
    // 释放时，移除监听按钮
    deinit {
     
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    // MARK: - 懒加载
    /// 工具栏
    private lazy var toolBar = UIToolbar()
    /// 文本框
    private lazy var textView: UITextView = {
        let tv = UITextView()
        
        tv.font = UIFont.systemFontOfSize(18)
        tv.textColor = UIColor.darkGrayColor()
        
        // 允许拉动
        tv.alwaysBounceVertical = true
        // 增加键盘消失的模式
        tv.keyboardDismissMode = .OnDrag
        
        // 设置文本代理
        tv.delegate = self
        
        return tv
    }()
    /// 占位字符
    private lazy var placeHolder: UILabel = UILabel(title: "分享新鲜事", color: UIColor.lightGrayColor(), fontSize: 18)
    //
    private lazy var emoticonView: EmoticonView = EmoticonView { [weak self] (emoticon) -> () in
        self?.textView.insertEmoticon(emoticon)
    }
}

extension ComposeViewController: UITextViewDelegate {
    
    func textViewDidChange(textView: UITextView) {
        
            navigationItem.rightBarButtonItem?.enabled = textView.hasText()
            placeHolder.hidden = textView.hasText()
       
    }
}

// MARK: - 设置界面
private extension ComposeViewController {
    
    func setupUI() {
        // 0 设置背景颜色 - 除去卡的效果
        view.backgroundColor = UIColor.whiteColor()
        
        // 1 准备控件
        setNavigationBar()
        prepareToolBar()
        prepareTextView()
    }
    
    ///  设置导航栏
    func setNavigationBar() {
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: .Plain, target: self, action: "close")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发布", style: .Plain, target: self, action: "compose")
        
        let titleView = UIView(frame: CGRectMake(0, 0, 100, 44))
        
        let titleLabel = UILabel(title: "发微博", color: UIColor.blackColor(), fontSize: 17)
        let nameLabel = UILabel(title: (UserAccountViewModel.shareAccount.account?.screen_name)!, color: UIColor.lightGrayColor())
        // 初始默认发微博
        navigationItem.rightBarButtonItem?.enabled = false
        
        titleView.addSubview(titleLabel)
        titleView.addSubview(nameLabel)
        
        titleLabel.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(titleView.snp_centerX)
            make.top.equalTo(titleView.snp_top).offset(4)
        }
        nameLabel.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(titleView.snp_centerX)
            make.bottom.equalTo(titleView.snp_bottom).offset(-4)
        }
        
        navigationItem.titleView = titleView
    }
    
    ///  准备工具栏
    func prepareToolBar() {
        // 0 设置背景
        toolBar.backgroundColor = UIColor(white: 0.8, alpha: 1)
        
        // 1 添加控件
        view.addSubview(toolBar)
        
        // 2 自动布局
        toolBar.snp_makeConstraints { (make) -> Void in
            make.left.equalTo(view.snp_left)
            make.right.equalTo(view.snp_right)
            make.bottom.equalTo(view.snp_bottom)
            make.height.equalTo(44)
        }
        
        // 3. 添加按钮
        let itemSettings = [["imageName": "compose_toolbar_picture"],
            ["imageName": "compose_mentionbutton_background"],
            ["imageName": "compose_trendbutton_background"],
            ["imageName": "compose_emoticonbutton_background", "actionName": "selectEmoticon"],
            ["imageName": "compose_addbutton_background"]]
        
        var items = [UIBarButtonItem]()
        for item in itemSettings {

            items.append(UIBarButtonItem(imageName: item["imageName"]!, target: self, selecter: item["actionName"]))
            
            items.append(UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil))
        }
        items.removeLast()
        toolBar.items = items
    }
    
    ///  准备文本框
    func prepareTextView() {
        // 添加控件
        view.addSubview(textView)
        
        // 自动布局
        textView.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(self.snp_topLayoutGuideBottom)
            make.left.equalTo(view.snp_left)
            make.right.equalTo(view.snp_right)
            make.bottom.equalTo(toolBar.snp_top)
        }
        
        // 准备占位字符
        textView.addSubview(placeHolder)
        placeHolder.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(textView.snp_top).offset(8)
            make.left.equalTo(textView.snp_left).offset(5)
        }
    }
}











